package com.xiaoq.shop.endpoint;

import com.alibaba.dubbo.config.annotation.Reference;
import com.xiaoq.apis.interpreter.IInterpreterApi;
import com.xiaoq.apis.user.IUserApi;
import com.xiaoq.apis.user.UserInfo4UserCouponVo;
import com.xiaoq.coms.GenericDataResponse;
import com.xiaoq.coms.GenericResponse;
import com.xiaoq.coms.util.ConstantUtil;
import com.xiaoq.order.entity.ShopOrderEntity;
import com.xiaoq.order.service.IShopOrderService;
import com.xiaoq.shop.entity.SPUReviewEntity;
import com.xiaoq.shop.service.ISPUReviewService;
import com.xiaoq.shop.service.ISPUService;
import com.xiaoq.shop.vo.SPUReviewScoreVo;
import io.swagger.annotations.*;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;

/**
 * Created by chenjh on 2017/11/28.
 */
@Api(tags = "订单的评论,打分,评分")
@RestController
@RequestMapping(value = "/api/v1/shops")
public class SPUReviewEndpoint2C {

    private static final Logger LOGGER = LoggerFactory.getLogger(SPUReviewEndpoint2C.class);
    private static final class SPUReviewScoreDataResponse extends GenericDataResponse<SPUReviewScoreVo> {};

    @Autowired
    private ISPUReviewService spuReviewService;

    @Autowired
    private IShopOrderService orderService;

    @Reference(interfaceClass=IUserApi.class, check=false, version="1.0.0")
    private IUserApi userDubboApi;

    @Autowired
    private ISPUService spuService;

    @Reference(interfaceClass=IInterpreterApi.class, check=false, version="1.0.0")
    private IInterpreterApi interpreterApi;

    //评论订单
    @ApiOperation(value="评论订单", notes="评论订单")
    @ApiResponses({
            @ApiResponse(code = 200, response = GenericResponse.class, message = "评论订单")
    })
    @RequestMapping(value = "/{shopId}/reviews",method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseEntity<?> reviewOrder(
            HttpServletRequest request,
            @ApiParam(required = true,name = "shopId",value = "小店id")
            @PathVariable String shopId,
            @ApiParam(required = true,name = "orderId",value = "订单id")
            @RequestParam String orderId,
            @ApiParam(required = true,name = "spuCode",value = "商品SPU编码")
            @RequestParam String spuCode,
            @ApiParam(required = true,name = "reviewJson",value = "评论json串")
            @RequestBody SPUReviewEntity spuReviewEntity) {


        LOGGER.info("spuReviewEntity: " + spuReviewEntity);
        String userId = (String) request.getAttribute("userId");

        ShopOrderEntity orderEntity = orderService.getShopOrderById(orderId, userId);
        if(orderEntity == null){
            return GenericResponse.ng("此订单不存在");
        }

        boolean successFlag = false;
        if(ConstantUtil.ORDER_TYPE_INTERPRETER.equals(orderEntity.getOrderType())){
            //评论讲解员
            successFlag = spuReviewService.commitComment(userId,shopId,orderId,spuCode,spuReviewEntity);

            if(successFlag){
                try {
                    interpreterApi.updateInterCalendarStatus(orderId, ConstantUtil.INTERPRETER_CALENDAR_STATUS_HAVA_review_);
                }catch (Exception e){
                    LOGGER.error("修改讲解员日历至已评论状态失败");
                    LOGGER.error(e.getMessage(), e);
                }
            }

        }else if(ConstantUtil.ORDER_TYPE_TICKET.equals(orderEntity.getOrderType())){
            //评论购票
            successFlag = spuReviewService.commitComment(userId,shopId,orderId,spuCode,spuReviewEntity);
        }
        if(successFlag){
            return GenericResponse.ok();
        }
        LOGGER.error("评论添加失败。userId: " + userId + ",orderId: " + orderId);
        return GenericResponse.ng("评论添加失败");
    }

    @ApiOperation(value="获取景区评分", notes="获取景区评分")
    @ApiResponses({
            @ApiResponse(code = 200, response = SPUReviewScoreDataResponse.class, message = "获取景区评分")
    })
    @GetMapping(value = "/{shopId}/scorestat", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseEntity<?> shopScoreStat(
            HttpServletRequest request,
            @ApiParam(required = true, name = "shopId", value = "店ID")
            @PathVariable String shopId) {

        //TODO catalogCode 暂时写死0
        SPUReviewScoreVo spuReviewScoreVo = spuService.getReviewScoreByShopIdAndCataCode(shopId, "0");
        if(spuReviewScoreVo == null){
            spuReviewScoreVo = new SPUReviewScoreVo();
            spuReviewScoreVo.setScoreStatList(new ArrayList<>());
            return SPUReviewScoreDataResponse.okWithData(spuReviewScoreVo);
        }
        spuReviewScoreVo.setShopId(shopId);

        //20180130 产品需求,按照人数多的排前面,人数相同时,分数高的排前面
        if(CollectionUtils.isNotEmpty(spuReviewScoreVo.getScoreStatList())){
            spuReviewScoreVo.getScoreStatList().sort((o1, o2) -> {
                int i = o2.getNum() - o1.getNum();
                if(i == 0){
                    return o2.getScore() - o1.getScore();
                }
                return i;
            });
        }

        return SPUReviewScoreDataResponse.okWithData(spuReviewScoreVo);
    }
}
